import React, { useState, useEffect } from 'react';
import {
  Layout,
  Tabs,
  Button as AntButton,
  Input,
  Badge,
  Empty,
  Spin,
  App,
  Modal,
  InputNumber,
  Radio,
  Space,
  Divider,
  Typography,
  Switch
} from 'antd';
import {
  ArrowLeftOutlined,
  PlusOutlined,
  MinusOutlined,
  ShoppingCartOutlined,
  CheckOutlined,
  PrinterOutlined
} from '@ant-design/icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Card } from '../../components/common/Card';
import { Button } from '../../components/common/Button';
import { productService, tradeService } from '../../services';
import type {
  Product,
  ProductCategory,
  ProductVariant,
  ProductListParams,
  PaginationParams
} from '../../services/productService';
import './OrderDetailPage.css';

const { TabPane } = Tabs;
const { Search } = Input;
const { Text, Title } = Typography;

// 购物车商品项
interface CartItem {
  productId: number;
  productName: string;
  variantId?: number;
  variantName?: string;
  price: number;
  quantity: number;
  image?: string;
}

// 订单模式
type OrderMode = 'new' | 'add';

// 分类查询参数
interface CategoryListParams extends PaginationParams {
  status?: number;
}

export const OrderDetailPage: React.FC = () => {
  const [searchParams] = useSearchParams();
  const [categoryTab, setCategoryTab] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<ProductCategory[]>([]);
  const [cart, setCart] = useState<CartItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [categoriesLoading, setCategoriesLoading] = useState(true);
  const [variantModalVisible, setVariantModalVisible] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [selectedVariant, setSelectedVariant] = useState<ProductVariant | null>(null);
  const [quantity, setQuantity] = useState(1);
  const [submitting, setSubmitting] = useState(false);
  const [printOrder, setPrintOrder] = useState(true);

  const navigate = useNavigate();
  const { message } = App.useApp();

  // 从URL参数获取餐桌ID和模式
  const tableId = searchParams.get('tableId');
  const mode = (searchParams.get('mode') as OrderMode) || 'new';

  // 加载商品和分类数据
  useEffect(() => {
    fetchCategories();
  }, []);

  // 分类切换时重新加载商品
  useEffect(() => {
    fetchProducts();
  }, [categoryTab]);

  // 获取商品数据
  const fetchProducts = async () => {
    setLoading(true);
    try {
      const params: ProductListParams = {
        page: 1,
        pageSize: 100,
        status: 1,
        canBuy: 1
      };

      if (categoryTab !== 'all') {
        params.category = parseInt(categoryTab, 10);
      }

      const response = await productService.getProductList(params);
      if (response.code === 0 && response.data) {
        setProducts(response.data.list);
      } else {
        message.error(response.message || '获取商品失败');
      }
    } catch (error) {
      console.error('获取商品数据失败:', error);
      message.error('获取商品数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取分类数据
  const fetchCategories = async () => {
    setCategoriesLoading(true);
    try {
      const params: CategoryListParams = {
        page: 1,
        pageSize: 50,
        status: 1
      };

      const response = await productService.getCategoryList(params);
      if (response.code === 0 && response.data) {
        setCategories(response.data.list);
      } else {
        message.error(response.message || '获取分类失败');
      }
    } catch (error) {
      console.error('获取分类数据失败:', error);
      message.error('获取分类数据失败');
    } finally {
      setCategoriesLoading(false);
    }
  };

  // 过滤商品
  const filteredProducts = products.filter(product => {
    const matchesSearch = searchQuery === '' ||
      product.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (product.description && product.description.toLowerCase().includes(searchQuery.toLowerCase()));

    return matchesSearch && product.canBuy && product.status === 1;
  });

  // 处理商品点击
  const handleProductClick = (product: Product) => {
    if (product.variants && product.variants.length > 0) {
      // 有规格的商品，显示规格选择弹窗
      setSelectedProduct(product);
      setSelectedVariant(product.variants[0]);
      setQuantity(1);
      setVariantModalVisible(true);
    } else {
      // 无规格的商品，直接加入购物车
      addToCart({
        productId: product.id,
        productName: product.title,
        price: product.price,
        quantity: 1,
        image: product.image
      });
    }
  };

  // 加入购物车
  const addToCart = (item: CartItem) => {
    setCart(prevCart => {
      const existingIndex = prevCart.findIndex(
        cartItem =>
          cartItem.productId === item.productId &&
          cartItem.variantId === item.variantId
      );

      if (existingIndex >= 0) {
        // 商品已存在，增加数量
        const newCart = [...prevCart];
        newCart[existingIndex].quantity += item.quantity;
        return newCart;
      } else {
        // 新商品，添加到购物车
        return [...prevCart, item];
      }
    });
    message.success('已加入购物车');
  };

  // 确认添加规格商品
  const handleVariantConfirm = () => {
    if (!selectedProduct || !selectedVariant) return;

    addToCart({
      productId: selectedProduct.id,
      productName: selectedProduct.title,
      variantId: selectedVariant.id,
      variantName: selectedVariant.attributeValues.map((av: { value: string }) => av.value).join(' '),
      price: selectedVariant.price,
      quantity,
      image: selectedProduct.image
    });

    setVariantModalVisible(false);
    setSelectedProduct(null);
    setSelectedVariant(null);
    setQuantity(1);
  };

  // 更新购物车商品数量
  const updateCartQuantity = (productId: number, variantId: number | undefined, newQuantity: number) => {
    if (newQuantity <= 0) {
      // 删除商品
      setCart(prevCart =>
        prevCart.filter(item =>
          !(item.productId === productId && item.variantId === variantId)
        )
      );
    } else {
      // 更新数量
      setCart(prevCart =>
        prevCart.map(item =>
          item.productId === productId && item.variantId === variantId
            ? { ...item, quantity: newQuantity }
            : item
        )
      );
    }
  };

  // 计算购物车总价
  const getTotalAmount = () => {
    return cart.reduce((total, item) => total + item.price * item.quantity, 0);
  };

  // 提交订单
  const handleSubmitOrder = async () => {
    if (!tableId) {
      message.error('缺少餐桌信息');
      return;
    }

    if (cart.length === 0) {
      message.error('购物车为空');
      return;
    }

    setSubmitting(true);
    try {
      const tradeOrderList = cart.map(item => ({
        productId: item.productId,
        productName: item.productName,
        variantId: item.variantId,
        variantName: item.variantName,
        quantity: item.quantity
      }));

      const params = {
        channel: 'minipro',
        restaurantId: 1,
        tableId: parseInt(tableId, 10),
        tradeOrderList,
        remark: '',
        printOrder: printOrder ? 1 : 0
      };

      const response = await tradeService.createTrade(params);
      if (response.code === 0 && response.data) {
        message.success('订单创建成功');
        
        // 如果勾选了打印制作分单，则调用打印接口
        if (printOrder && response.data.id) {
          try {
            const printResponse = await tradeService.printTicket(response.data.id);
            if (printResponse.code === 0) {
              message.success('制作分单打印成功');
            } else {
              message.warning(`订单创建成功，但打印制作分单失败：${printResponse.message}`);
            }
          } catch (printError) {
            message.warning('订单创建成功，但打印制作分单失败');
            console.error('打印制作分单失败:', printError);
          }
        }
        
        // 清空购物车
        setCart([]);
        // 返回餐桌管理页面
        navigate('/order-station');
      } else {
        message.error(response.message || '创建订单失败');
      }
    } catch (error) {
      console.error('创建订单失败:', error);
      message.error('创建订单失败');
    } finally {
      setSubmitting(false);
    }
  };

  // 返回餐桌管理
  const handleBack = () => {
    navigate('/order-station');
  };

  // 渲染商品卡片
  const renderProductCard = (product: Product) => {
    // 获取商品的最低价格（如果有规格）
    const getProductPrice = () => {
      if (product.variants && product.variants.length > 0) {
        const prices = product.variants.map(v => v.price);
        const minPrice = Math.min(...prices);
        const maxPrice = Math.max(...prices);
        return minPrice === maxPrice ? `¥${minPrice}` : `¥${minPrice}-${maxPrice}`;
      }
      return `¥${product.price}`;
    };

    return (
      <Card
        key={product.id}
        className="product-card"
        onClick={() => handleProductClick(product)}
        style={{
          padding: 0
        }}
        bodyStyle={{
          padding: 0
        }}
      >
        <div className="product-image">
          {product.image ? (
            <img src={product.image} alt={product.title} />
          ) : (
            <div className="product-image-placeholder">
              <ShoppingCartOutlined />
            </div>
          )}
        </div>

        <div className="product-content">
          <div className="product-header">
            <h3 className="product-name" title={product.title}>{product.title}</h3>
            <div className="product-price">{getProductPrice()}</div>
          </div>

          {product.description && (
            <div className="product-description" title={product.description}>
              {product.description}
            </div>
          )}

          <div className="product-footer">
            <div className="product-stock">库存: {product.stock}</div>
            <Button
              variant="primary"
              size="small"
              icon={<PlusOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleProductClick(product);
              }}
            >
              选择
            </Button>
          </div>
        </div>
      </Card>
    );
  };

  // 渲染分类 Tabs
  const renderCategoryTabs = () => {
    return (
      <Tabs
        className="category-tabs"
        activeKey={categoryTab}
        onChange={setCategoryTab}
        size="large"
      >
        <TabPane tab="全部商品" key="all" />
        {categories.map(category => (
          <TabPane tab={category.name} key={category.id.toString()} />
        ))}
      </Tabs>
    );
  };

  // 渲染购物车
  const renderCart = () => {
    const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);

    return (
      <div className="cart-section">
        <div className="cart-header">
          <Title level={4}>
            <ShoppingCartOutlined /> 购物车
            {totalItems > 0 && <Badge count={totalItems} />}
          </Title>
        </div>

        <div className="cart-content">
          {cart.length === 0 ? (
            <Empty description="购物车为空" image={Empty.PRESENTED_IMAGE_SIMPLE} />
          ) : (
            <div className="cart-items">
              {cart.map((item) => (
                <div key={`${item.productId}-${item.variantId || 0}`} className="cart-item">
                  <div className="cart-item-info">
                    <div className="cart-item-name" title={item.productName}>
                      {item.productName}
                    </div>
                    {item.variantName && (
                      <div className="cart-item-variant">{item.variantName}</div>
                    )}
                    <div className="cart-item-price">¥{item.price} × {item.quantity}</div>
                  </div>

                  <div className="cart-item-controls">
                    <AntButton
                      size="small"
                      icon={<MinusOutlined />}
                      onClick={() => updateCartQuantity(item.productId, item.variantId, item.quantity - 1)}
                    />
                    <span className="cart-item-quantity">{item.quantity}</span>
                    <AntButton
                      size="small"
                      icon={<PlusOutlined />}
                      onClick={() => updateCartQuantity(item.productId, item.variantId, item.quantity + 1)}
                    />
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {cart.length > 0 && (
          <div className="cart-footer">
            <div className="cart-total">
              <Text strong>共 {totalItems} 件商品，总计: ¥{getTotalAmount().toFixed(2)}</Text>
            </div>
            
            <div className="print-option">
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <PrinterOutlined />
                <Text>下单后打印制作分单</Text>
              </div>
              <Switch 
                checked={printOrder}
                onChange={setPrintOrder}
                size="small"
              />
            </div>
            
            <Button
              variant="primary"
              size="large"
              loading={submitting}
              onClick={handleSubmitOrder}
              icon={<CheckOutlined />}
              style={{ width: '100%' }}
            >
              {mode === 'new' ? '下单' : '加单'}
            </Button>
          </div>
        )}
      </div>
    );
  };

  return (
    <Layout className="order-detail-layout">
      <div className="order-detail-header">
        <div className="header-left">
          <AntButton
            className="back-button"
            type="text"
            icon={<ArrowLeftOutlined />}
            size="large"
            onClick={handleBack}
          />
          <h1 className="page-title">
            {mode === 'new' ? '点餐' : '加单'} - 餐桌{tableId}
          </h1>
        </div>
      </div>

      <div className="main-container">
        <div className="content-wrapper">
          <div className="products-section">
            <div className="search-container">
              <Search
                placeholder="搜索商品..."
                allowClear
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onSearch={setSearchQuery}
                size="large"
                className="search-input"
              />
            </div>

            {/* 分类筛选标签页 */}
            {categoriesLoading ? (
              <div className="loading-container">
                <Spin size="large" tip="加载分类中..." />
              </div>
            ) : (
              renderCategoryTabs()
            )}

            <div className="products-grid">
              {loading ? (
                <div className="loading-container">
                  <Spin size="large" tip="加载商品中..." />
                </div>
              ) : filteredProducts.length > 0 ? (
                filteredProducts.map(renderProductCard)
              ) : (
                <div className="empty-container">
                  <Empty
                    description="没有找到符合条件的商品"
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                  />
                </div>
              )}
            </div>
          </div>

          {renderCart()}
        </div>
      </div>

      {/* 规格选择弹窗 */}
      <Modal
        title={`选择规格 - ${selectedProduct?.title || ''}`}
        open={variantModalVisible}
        onOk={handleVariantConfirm}
        onCancel={() => setVariantModalVisible(false)}
        okText="加入购物车"
        cancelText="取消"
        width={500}
        okButtonProps={{
          disabled: !selectedVariant,
          size: 'large'
        }}
        cancelButtonProps={{
          size: 'large'
        }}
      >
        {selectedProduct && (
          <div className="variant-modal-content">
            <div className="product-info">
              {selectedProduct.image && (
                <div style={{ textAlign: 'center', marginBottom: 16 }}>
                  <img
                    src={selectedProduct.image}
                    alt={selectedProduct.title}
                    style={{
                      width: 120,
                      height: 120,
                      objectFit: 'cover',
                      borderRadius: 8
                    }}
                  />
                </div>
              )}
              <Title level={4} style={{ marginBottom: 8 }}>{selectedProduct.title}</Title>
              {selectedProduct.description && (
                <Text type="secondary" style={{ fontSize: 13, lineHeight: 1.4 }}>
                  {selectedProduct.description}
                </Text>
              )}
            </div>

            <Divider />

            <div className="variant-selection">
              <Text strong style={{ fontSize: 15 }}>选择规格</Text>
              <Radio.Group
                value={selectedVariant?.id}
                onChange={(e) => {
                  const variant = selectedProduct.variants?.find(v => v.id === e.target.value);
                  setSelectedVariant(variant || null);
                }}
                style={{ width: '100%', marginTop: 12 }}
              >
                <Space direction="vertical" style={{ width: '100%' }}>
                  {selectedProduct.variants?.map(variant => (
                    <Radio key={variant.id} value={variant.id} style={{ width: '100%' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
                        <span>{variant.attributeValues.map((av: { value: string }) => av.value).join(' ')}</span>
                        <div style={{ color: '#ff4d4f', fontSize: 16, fontWeight: 600, marginLeft: 10 }}>¥{variant.price}</div>
                      </div>
                    </Radio>
                  ))}
                </Space>
              </Radio.Group>
            </div>

            <Divider />

            <div className="quantity-selection">
              <Text strong style={{ fontSize: 15 }}>数量</Text>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 12 }}>
                <AntButton
                  icon={<MinusOutlined />}
                  onClick={() => setQuantity(Math.max(1, quantity - 1))}
                  disabled={quantity <= 1}
                />
                <InputNumber
                  min={1}
                  value={quantity}
                  onChange={(value) => setQuantity(value || 1)}
                  style={{ width: 80, textAlign: 'center' }}
                />
                <AntButton
                  icon={<PlusOutlined />}
                  onClick={() => setQuantity(quantity + 1)}
                />
              </div>
            </div>

            {selectedVariant && (
              <div className="variant-total">
                <Text strong style={{ fontSize: 16 }}>
                  小计: ¥{(selectedVariant.price * quantity).toFixed(2)}
                </Text>
              </div>
            )}
          </div>
        )}
      </Modal>
    </Layout>
  );
};

export default OrderDetailPage; 